<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-19 11:11:00
 * @LastEditTime: 2022-04-19 18:58:29
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 单实例模式
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>单实例模式</title>
</head>

<body>

</body>
<script>
  // 划分命名空间,并将属性和方法组织在一起的一种方式
  // 只是实例化一次,每次返回的实例都是同一对象

  // // 构造函数
  // function Singleton(name) {
  //   this.name = name
  // }
  // Singleton.prototype.getName = function () {
  //   console.log(this.name);
  // }
  // // 静态方法
  // Singleton.getInstance = function (name) {
  //   if (!this.instance) {
  //     this.instance = new Singleton(name)
  //   }
  //   return this.instance
  // }


  /* ES6 改写 */
  class Singleton {
    constructor(name) {
      this.name = name
    }
    getName() {
      console.log(this.name);
    }
    static X(name) {
      if (!this.instance) {
        this.instance = new Singleton(name)
      }
      return this.instance
    }
  }
  const a1 = Singleton.getInstance('张三')
  const a2 = Singleton.getInstance('李四')

  
  console.log(a1, a2);
  console.log(a1 == a2);
  a1.getName()
</script>

</html>